import React, { useRef, useEffect, useState } from 'react';
import { fabric } from 'fabric';
import { Button, Tooltip, Space, message } from 'antd';
import { BorderOutlined, CheckCircleOutlined, CloseCircleOutlined, FontSizeOutlined, ClearOutlined, WifiOutlined, DisconnectOutlined, UserOutlined } from '@ant-design/icons';

import { setupCollaboration } from '../../coordination/SimpleCollaboration';
import './canvas.css';

const TestCanvas = () => {
    const canvasRef = useRef(null);
    const fabricRef = useRef(null);
  const [currentTool, setCurrentTool] = useState(null);
  const [isConnected, setIsConnected] = useState(false);
  const [onlineUsers, setOnlineUsers] = useState([]);
  const collaborationRef = useRef(null);
  const [canvasReady, setCanvasReady] = useState(false);
  // 存储 handleResize 引用以便清理
  const handleResizeRef = useRef(null);

  // 初始化Fabric画布
  useEffect(() => {
    // 确保DOM已经渲染完成
    const initCanvas = () => {
      if (!canvasRef.current) {
        console.warn('Canvas元素未找到，延迟初始化');
        setTimeout(initCanvas, 100);
                return;
            }

      try {
        console.log('初始化画布...');
        fabricRef.current = new fabric.Canvas(canvasRef.current, {
          width: window.innerWidth - 60,
          height: window.innerHeight - 100,
          backgroundColor: '#f5f5f5'
        });

        // 确保对象有唯一ID
        fabricRef.current.on('object:added', (e) => {
          if (e.target && !e.target.id) {
            e.target.id = `obj_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
          }
        });

        // 窗口大小调整处理
        const handleResize = () => {
        if (fabricRef.current) {
            fabricRef.current.setWidth(window.innerWidth - 60);
            fabricRef.current.setHeight(window.innerHeight - 100);
            fabricRef.current.requestRenderAll();
          }
        };
        
        // 保存引用以便清理
        handleResizeRef.current = handleResize;
        window.addEventListener('resize', handleResize);
        
        // 标记画布已准备就绪
        setCanvasReady(true);
        } catch (error) {
        console.error('初始化画布时出错:', error);
        message.error('初始化画布时出错');
      }
    };

    initCanvas();

    return () => {
      if (handleResizeRef.current) {
        window.removeEventListener('resize', handleResizeRef.current);
      }
      
      if (fabricRef.current) {
        fabricRef.current.dispose();
        fabricRef.current = null;
      }
      
      // 清理协作
      if (collaborationRef.current) {
        const { wsProvider } = collaborationRef.current;
        wsProvider.disconnect();
      }
      
      // 移除事件监听器
      document.removeEventListener('userListUpdated', handleUserListUpdate);
    };
    }, []);

  // 处理用户列表更新的函数
  const handleUserListUpdate = (event) => {
    if (event.detail && event.detail.users) {
      setOnlineUsers(event.detail.users);
    }
  };

  // 初始化Yjs协作 - 仅在画布准备就绪后执行
  useEffect(() => {
    if (!canvasReady || !fabricRef.current) return;

    const initializeCollaboration = () => {
      try {
        console.log('初始化协作...');
        // 设置协作
        collaborationRef.current = setupCollaboration(fabricRef.current, 'test-room');
        
        // 使用自定义事件监听连接状态
        const handleConnectionStatus = (event) => {
          if (event.detail && event.detail.status) {
            const status = event.detail.status;
            console.log(`收到连接状态更新: ${status}`);
            setIsConnected(status === 'connected');
            
            if (status === 'connected') {
              message.success('已连接到协作服务器');
            } else if (status === 'disconnected') {
              message.warning('已断开协作服务器连接');
            }
          }
        };
        
        // 添加自定义事件监听器
        document.addEventListener('collaboration-status-changed', handleConnectionStatus);
        
        // 30秒后手动检查连接状态
                    setTimeout(() => {
          if (collaborationRef.current && collaborationRef.current.checkConnection) {
            collaborationRef.current.checkConnection();
          }
        }, 3000);

        // 监听用户列表更新
        document.addEventListener('userListUpdated', handleUserListUpdate);
        
        // 清理函数
        return () => {
          document.removeEventListener('collaboration-status-changed', handleConnectionStatus);
        };
            } catch (error) {
        console.error('初始化协作失败:', error);
        message.error('初始化协作失败');
      }
    };

    const cleanup = initializeCollaboration();
    
        return () => {
      if (cleanup) cleanup();
    };
  }, [canvasReady]);

  // 添加矩形
  const addRectangle = () => {
    if (!fabricRef.current) return;
    
    const rect = new fabric.Rect({
      left: 100,
      top: 100,
                    width: 100,
      height: 80,
      fill: getRandomColor(),
      stroke: '#000',
      strokeWidth: 1
    });
    fabricRef.current.add(rect);
    fabricRef.current.setActiveObject(rect);
  };

  // 添加圆形
  const addCircle = () => {
    if (!fabricRef.current) return;
    
    const circle = new fabric.Circle({
      left: 100,
      top: 100,
      radius: 50,
      fill: getRandomColor(),
      stroke: '#000',
      strokeWidth: 1
    });
    fabricRef.current.add(circle);
    fabricRef.current.setActiveObject(circle);
  };

  // 添加三角形
  const addTriangle = () => {
    if (!fabricRef.current) return;
    
    const triangle = new fabric.Triangle({
      left: 100,
      top: 100,
      width: 100,
      height: 100,
      fill: getRandomColor(),
      stroke: '#000',
      strokeWidth: 1
    });
    fabricRef.current.add(triangle);
    fabricRef.current.setActiveObject(triangle);
  };

  // 添加文本
  const addText = () => {
    if (!fabricRef.current) return;
    
    const text = new fabric.IText('编辑文本', {
      left: 100,
      top: 100,
      fontFamily: 'Arial',
      fontSize: 20,
      fill: '#000000'
    });
    fabricRef.current.add(text);
    fabricRef.current.setActiveObject(text);
  };

  // 清空画布
  const clearCanvas = () => {
        if (!fabricRef.current) return;
    fabricRef.current.clear();
  };

  // 生成随机颜色
  const getRandomColor = () => {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  };

  // 切换工具
  const handleToolSelect = (tool) => {
    setCurrentTool(tool);
    
    switch (tool) {
      case 'rectangle':
        addRectangle();
        break;
      case 'circle':
        addCircle();
        break;
      case 'triangle':
        addTriangle();
        break;
      case 'text':
        addText();
        break;
      case 'clear':
        clearCanvas();
        break;
      default:
        break;
    }
  };

    return (
    <div className="canvas-container">
      <div className="toolbar">
        <Space>
          <Tooltip title="矩形">
            <Button
              type={currentTool === 'rectangle' ? 'primary' : 'default'}
              icon={<BorderOutlined />}
              onClick={() => handleToolSelect('rectangle')}
            />
          </Tooltip>
          <Tooltip title="圆形">
            <Button
              type={currentTool === 'circle' ? 'primary' : 'default'}
              icon={<CheckCircleOutlined />}
              onClick={() => handleToolSelect('circle')}
            />
          </Tooltip>
          <Tooltip title="三角形">
                                    <Button
              type={currentTool === 'triangle' ? 'primary' : 'default'}
              icon={<CloseCircleOutlined />}
              onClick={() => handleToolSelect('triangle')}
            />
          </Tooltip>
          <Tooltip title="文本">
            <Button
              type={currentTool === 'text' ? 'primary' : 'default'}
              icon={<FontSizeOutlined />}
              onClick={() => handleToolSelect('text')}
            />
          </Tooltip>
          <Tooltip title="清空画布">
            <Button
                                        danger
              icon={<ClearOutlined />}
              onClick={() => handleToolSelect('clear')}
            />
          </Tooltip>
          
          {/* 显示连接状态 */}
          <Tooltip title={isConnected ? '已连接到协作服务器' : '未连接到协作服务器'}>
            <Button
              type={isConnected ? 'primary' : 'default'}
              icon={isConnected ? <WifiOutlined /> : <DisconnectOutlined />}
              style={{ color: isConnected ? '#52c41a' : '#ff4d4f' }}
            >
              {isConnected ? '已连接' : '未连接'}
                                    </Button>
          </Tooltip>
          
          {/* 显示在线用户数量 */}
          <Tooltip title={`在线用户: ${onlineUsers.length}`}>
            <Button icon={<UserOutlined />}>
              {onlineUsers.length}
            </Button>
          </Tooltip>
        </Space>
                            </div>
      
      <div className="canvas-wrapper">
        <canvas ref={canvasRef} id="fabric-canvas"></canvas>
                        </div>
      
      {/* 显示协作状态提示 */}
      {!isConnected && (
        <div className="collaboration-alert">
          <p>未连接到协作服务器，请确保服务器已启动</p>
          <p>启动命令: npm run simple-server</p>
                    </div>
      )}
                </div>
    );
};

export default TestCanvas;
